package ysq.xyg.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import ysq.xyg.model.BaseMenu;
import ysq.xyg.model.info.BaseMenuInfo;
import ysq.xyg.model.info.Page;
import ysq.xyg.model.info.ReturnInfo;
import ysq.xyg.service.BaseMenuService;
import ysq.xyg.util.BaseConstant;
import ysq.xyg.util.BaseUtil;
import ysq.xyg.util.DateUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Yu Shengqiang on 2017/5/3.
 */
@Controller
@RequestMapping("/baseMenu")
public class BaseMenuController  extends BaseController{
    private static Logger log= LoggerFactory.getLogger(BaseMenuController.class);
    @Resource
    private BaseMenuService baseMenuService;
    private BaseMenu baseMenu;

    @RequestMapping("/listPage")
    public ModelAndView listPage(HttpServletRequest request, HttpServletResponse response,String menuid){
        return new ModelAndView("/baseMenuList").addObject("headTitle",acceptTitle(menuid,baseMenuService));
    }

    @RequestMapping(value = "/menuList")
    public @ResponseBody
    JSONObject menuList(String  departId,String menuId) throws UnsupportedEncodingException {
        //菜单查询
        BaseMenu baseMenu=new BaseMenu();
        baseMenu.setRemovetag(BaseConstant.REMOVE_N);
        baseMenu.setIsNotGrade(BaseConstant.MENU_ONE);
        baseMenu.setParentmenuid(menuId);
        baseMenu.setDepartId(departId);
        List<BaseMenu> baseMenuList=baseMenuService.selectEntityByLeft(baseMenu);
        JSONObject jsonObject=new JSONObject();
        JSONArray rows = new JSONArray();
        for (BaseMenu baseMenu1:baseMenuList){
            JSONObject row=new JSONObject();
            row.put("title",baseMenu1.getMenuname());
            row.put("icon",baseMenu1.getMenusign());
            row.put("href",baseMenu1.getMenuurl());
            row.put("spread",false);
            rows.add(row);
        }
        jsonObject.put("rows",rows);
        return jsonObject;
    }
    @RequestMapping(value = "/JsonList",method = RequestMethod.POST)
    public @ResponseBody
    JSONObject JsonList(BaseMenu baseMenu, Page page) throws UnsupportedEncodingException {
        baseMenu.setRemovetag(BaseConstant.REMOVE_N);
        PageInfo<BaseMenu> pageInfo=baseMenuService.pageInfo(baseMenu,page.getLimit(),page.getPage());
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("code",0);
        jsonObject.put("msg","");
        jsonObject.put("count",pageInfo.getTotal());
        if(pageInfo !=null && pageInfo.getList() !=null && pageInfo.getList().size() > 0){
            JSONObject row = null;
            JSONArray rows = new JSONArray();
            List<BaseMenu> baseMenusList=pageInfo.getList();
            List<BaseMenu> baseMenusLists=new ArrayList<BaseMenu>();
            if(baseMenusList!=null && baseMenusList.size() > 0){
                for(BaseMenu baseMenu1:baseMenusList){
                    if(BaseConstant.MENU_ONE.equals(baseMenu1.getMenugrade())){
                        baseMenusLists.add(baseMenu1);
                        for(BaseMenu baseMenu2:baseMenusList){
                            if(baseMenu1.getMenuid().equals(baseMenu2.getParentmenuid())){
                                baseMenusLists.add(baseMenu2);
                            }
                        }
                    }
                }
            }

            for(BaseMenu item:baseMenusLists){
                row=new JSONObject();
                row.put("menuid",item.getMenuid());
                row.put("menuname",item.getMenuname());
                row.put("menugrade",item.getMenugrade());
                row.put("menuurl",item.getMenuurl());
                row.put("menusign",item.getMenusign());
                row.put("menunum",item.getMenunum());
                row.put("menucode",item.getMenucode());
                row.put("parentmenuid",item.getParentmenuid());
                row.put("createtime", DateUtil.DateToStr(item.getCreatetime(),DateUtil.DATE_TIME_PATTERN));
                rows.add(row);
            }
            jsonObject.put("data",rows);
        }
        return jsonObject;
    }
    @RequestMapping(value = "/SelectEntity",method = RequestMethod.GET)
    public ModelAndView SelectEntity(String menuId,String parentId){
        ModelAndView view=new ModelAndView("/baseMenuUpdateOrSave");
        if (menuId != null && !"".equals(menuId)){
            BaseMenu baseMenu=(BaseMenu)baseMenuService.selectByPrimaryKey(menuId);
            view.addObject(baseMenu);
        }
        if(StringUtil.isNotEmpty(parentId)){
            baseMenu=new BaseMenu();
            baseMenu.setParentmenuid(parentId);
            view.addObject(baseMenu);
        }
        return view;
    }
    @RequestMapping(value = "/UpdateOrAddEntity",method = RequestMethod.POST)
    public @ResponseBody JSONObject UpdateOrAddEntity(BaseMenuInfo baseMenuInfo){
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();

        if(baseMenuInfo.getMenuid()==null || "".equals(baseMenuInfo.getMenuid())){

            baseMenu=new BaseMenu();
            baseMenu.setMenuid(BaseUtil.uId());
            baseMenu.setCreatetime(new Date());
            baseMenu.setRemovetag(BaseConstant.REMOVE_N);
            baseMenu.setMenuname(baseMenuInfo.getMenuname());
            baseMenu.setMenuurl(baseMenuInfo.getMenuurl());
            baseMenu.setMenunum(baseMenuInfo.getMenunum());
            baseMenu.setParentmenuid(baseMenuInfo.getParentmenuid());

            baseMenu.setMenusign(baseMenuInfo.getMenusign().replace("\"","'"));
            if(StringUtil.isNotEmpty(baseMenu.getParentmenuid())){
                BaseMenu parentBaseMenu=baseMenuService.selectByPrimaryKey(baseMenuInfo.getParentmenuid());
                //如果存在parentBaseMenu已存在子菜单
                BaseMenu record=new BaseMenu();
                record.setRemovetag(BaseConstant.REMOVE_N);
                record.setParentmenuid(parentBaseMenu.getMenuid());
                int info=baseMenuService.selectCount(record);
                if (info!=0){
                    baseMenu.setMenucode(baseMenuService.AcceptMaxMenuCode(baseMenuInfo.getParentmenuid(),Integer.parseInt(parentBaseMenu.getMenugrade())+1+""));
                }else{
                    baseMenu.setMenucode(parentBaseMenu.getMenucode()+baseMenuService.AcceptMaxMenuCode(baseMenuInfo.getParentmenuid(),Integer.parseInt(parentBaseMenu.getMenugrade())+1+""));
                }
                baseMenu.setMenugrade(Integer.parseInt(parentBaseMenu.getMenugrade())+1+"");
            }else{
                baseMenu.setMenucode(baseMenuService.AcceptMaxMenuCode(null));//menu_one是一级菜单
                baseMenu.setMenugrade(BaseConstant.MENU_ONE);
            }
            int id=baseMenuService.insert(baseMenu);
            if(id <= 0){
                returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_INSERT);
            }
        }else{
            baseMenu=baseMenuService.selectByPrimaryKey(baseMenuInfo.getMenuid());
            if(StringUtil.isEmpty(baseMenu.getMenucode())){
                if(baseMenu.getMenugrade()==BaseConstant.MENU_ONE){
                    baseMenu.setMenucode(baseMenuService.AcceptMaxMenuCode(baseMenu.getParentmenuid(),baseMenu.getMenugrade()));
                }else{
                    BaseMenu parentBaseMenu=baseMenuService.selectByPrimaryKey(baseMenuInfo.getParentmenuid());
                    baseMenu.setMenucode(baseMenuService.AcceptMaxMenuCode(baseMenu.getParentmenuid(),baseMenu.getMenugrade()));
                }
            }
            baseMenu.setMenuname(baseMenuInfo.getMenuname());
            baseMenu.setMenuurl(baseMenuInfo.getMenuurl());
            baseMenu.setMenunum(baseMenuInfo.getMenunum());
            baseMenu.setMenusign(baseMenuInfo.getMenusign().replace("\"","'"));
            baseMenu.setCreatetime(new Date());
            int id=baseMenuService.updateByPrimaryKey(baseMenu);
            if(id <= 0){
                returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_UPDATE);
            }
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }
    @RequestMapping(value = "/DeleteEntity",method = RequestMethod.GET)
    public @ResponseBody JSONObject DeleteEntity(String menuId){
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(StringUtil.isEmpty(menuId)){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_CANSHU);
        }else{
            BaseMenu baseMenu=baseMenuService.selectByPrimaryKey(menuId);
            if(baseMenu == null){
                returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_BUCHUNZAI);
            }else{
                baseMenu.setRemovetag(BaseConstant.REMOVE_Y);
                int id=baseMenuService.updateByPrimaryKey(baseMenu);
                if(id <= 0){
                    returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_DELETE);
                }
            }
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }


}
